package kr.pfg.applications.captureyourscreen.load
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.system.System;

	public class XMLLoader extends EventDispatcher
	{
		private var xml: XML;
		private var xmlUrl: String;
		private var xmlLoader: URLLoader;
		private var isConnected: Boolean;
		private var request: URLRequest;

		public function XMLLoader( url: String = null )
		{
			xmlUrl = url;
			System.useCodePage = true;
			init();
		}
		private function init(): void
		{
			if( xmlUrl ) load( xmlUrl );
		}
		public function load( url: String = null ): void
		{
			if( url ) request = new URLRequest( url );
			xml = new XML();
			xmlLoader = new URLLoader();
			xmlLoader.addEventListener( Event.COMPLETE,						onCompleteHandler );
			xmlLoader.addEventListener( Event.OPEN, 						onOpenHandler );
			xmlLoader.addEventListener( HTTPStatusEvent.HTTP_STATUS,		onHttpHandler );
			xmlLoader.addEventListener( ProgressEvent.PROGRESS,				onProgressHandler );
			xmlLoader.addEventListener( SecurityErrorEvent.SECURITY_ERROR, 	onSecurityHandler );
			xmlLoader.addEventListener( IOErrorEvent.IO_ERROR,				onIoErrorHandler );
			xmlLoader.load( request );
		}
		public function getResult(): XML
		{
			return xml;
		}
		public function stop(): void
		{
			if( isConnected ) xmlLoader.close();
			isConnected = false;
		}
		private function onCompleteHandler( e: Event ): void
		{
			xml = new XML( xmlLoader.data );
			isConnected = false;
			if( e != null ) dispatchEvent( new Event( Event.COMPLETE ) );
		}
		private function onOpenHandler( e: Event ): void
		{
			isConnected = true;
			if( e != null ) dispatchEvent( new Event( Event.OPEN ) );
		}
		private function onHttpHandler( e: HTTPStatusEvent ): void
		{
			dispatchEvent( new HTTPStatusEvent( HTTPStatusEvent.HTTP_STATUS ) );
		}
		private function onProgressHandler( e: ProgressEvent ): void
		{
			dispatchEvent( new ProgressEvent( ProgressEvent.PROGRESS ) );
		}
		private function onSecurityHandler( e: SecurityErrorEvent ): void
		{
			dispatchEvent( new SecurityErrorEvent( SecurityErrorEvent.SECURITY_ERROR ) );
		}
		private function onIoErrorHandler( e: IOErrorEvent ): void
		{
			dispatchEvent( new IOErrorEvent( IOErrorEvent.IO_ERROR ) );
		}
	}
}